package com.ks.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @Author：Administrator
 * @Date：2022/4/7/0007 22:15
 * @Versiion：1.0
 */
@Component
public class MyLb implements LoadBalancer {

    private AtomicInteger atomicInteger ;

    public MyLb() {
        atomicInteger = new AtomicInteger(0);
    }

    public final int getAndInstence(){
        int current;
        int next;
        for (;;){
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
            if (atomicInteger.compareAndSet(current, next)) {
                return next;
            }
        }
        /*do{
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
            //当原子类的值和current 不一致的时候就重新获取current  原子值和期望值一致就更新
        } while(!this.atomicInteger.compareAndSet(current, next));
        return next;*/
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstanceList) {
        return serviceInstanceList.get(getAndInstence() % serviceInstanceList.size());
    }
}
